package com.jt.service;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

@Service
public class MenuServiceImpl implements MenuService{
    @Autowired
    private MenuMapper menuMapper;

//    @Autowired
//    private RedisTemplate redisTemplate;

    @Resource(name="redisTemplate")
    private ValueOperations vo;

    // inject the template as ListOperations
    // can also inject as Value, Set, ZSet, and HashOperations
//    @Resource(name="redisTemplate")
//    private ListOperations<String, String> vo;

    @Override
    public Menu selectById(Long id) {
//        ValueOperations vo = redisTemplate.opsForValue();
        Menu m = (Menu)vo.get(String.valueOf(id));
        if (m!=null) {
            System.out.println("Get Data from redis");
            return m;}
        Menu menu = menuMapper.selectById(id);
        vo.set(String.valueOf(id), menu, Duration.ofSeconds(10));
        return menu;
    }

    @Override
    public Menu insertMenu(Menu menu) {
//        ValueOperations vo = redisTemplate.opsForValue();
        vo.set(String.valueOf(menu.getId()), menu, Duration.ofSeconds(10));
        menuMapper.insert(menu);
        return menu;
    }

    @Override
    public Menu updateMenu(Menu menu) {
//        ValueOperations vo = redisTemplate.opsForValue();
        vo.set(String.valueOf(menu.getId()), menu, Duration.ofSeconds(10));
        menuMapper.updateById(menu);
        return menu;
    }
}
